<?php

namespace frontend\modules\farmerhouse\controllers;

use common\components\Upload;
use common\models\business\BusinessAdress;
use common\models\business\BusinessUser;
use common\models\farmerhouse\FarmerhouseComment;
use common\models\farmerhouse\FarmerhouseHouse;
use common\models\farmerhouse\FarmerhouseTravels;
use common\models\farmerhouse\FarmerhouseTravelsDetail;
use common\models\shop\ShopHouseOrder;
use common\models\shop\ShopSlide;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Response;


/**
 * Class FarmerHoseController
 * @package frontend\modules\business\controllers
 * 农家乐相关控制器
 */
class SiteController extends BaseMobileController
{


    /**
     * @return string
     * 农家乐首页
     */
    public function actionIndex()
    {

        //取出农家乐分布的地区
        $address = BusinessAdress::find()->select('name,id')->where('type=:type',[':type' => BusinessAdress::TYPE_XIAN])->asArray()->all();
        foreach ($address as $key => $row){
            $address[$key]['url'] = Url::to(['/farmerhouse/site/list','addressid'=>$row['id']]);
        }


        //取出幻灯片
        $slids = ShopSlide::find()->select('picture as img')->where('type=:type',[':type'=>ShopSlide::TYPE_FARMERHOUSE])->asArray()->all();
        foreach ($slids as $key => $row)
        {
            $slids[$key]['img'] = Upload::checkGetUrl($row['img']);
        }


        if(\Yii::$app->request->get('recommand')){
            $houses = FarmerhouseHouse::find()
                ->select("id,name,price,envphoto as img,address")
                ->where('status=:status and isrecommand=1',[':status'=>FarmerhouseHouse::STATUS_AGREE])
                ->limit(10)
                ->asArray()
                ->all();
        }else{
            //取出农家乐
            $houses = FarmerhouseHouse::find()
                ->select("id,name,price,envphoto as img,address")
                ->where('status=:status',[':status'=>FarmerhouseHouse::STATUS_AGREE])
                ->limit(10)
                ->asArray()
                ->all();
        }

        foreach ($houses as $key => $row)
        {
            $houses[$key]['img']=  Upload::checkGetUrl($row['img']);
            $houses[$key]['url']=  Url::to(['/farmerhouse/site/house-detail','id'=>$row['id']]);
        }

        //客服电话
        $tel = SysSetting::getValue('housecustomertel');

        return $this->render('@template/mobile/farmhouse.html',[
            'slids' => \GuzzleHttp\json_encode(ArrayHelper::getColumn($slids,'img')),
            'houses' => \GuzzleHttp\json_encode($houses),
            'address' => \GuzzleHttp\json_encode($address),
            'tel' => $tel
        ]);
    }



    public function actionList($addressid)
    {
        //取出农家乐分布的地区
        $address = BusinessAdress::find()->select('name,id')->where('type=:type',[':type' => BusinessAdress::TYPE_XIAN])->asArray()->all();
        foreach ($address as $key => $row){
            $address[$key]['url'] = Url::to(['/farmerhouse/site/list','addressid'=>$row['id']]);
        }


        //取出幻灯片
        $slids = ShopSlide::find()->select('picture as img')->where('type=:type',[':type'=>ShopSlide::TYPE_FARMERHOUSE])->asArray()->all();
        foreach ($slids as $key => $row)
        {
            $slids[$key]['img'] = Upload::checkGetUrl($row['img']);
        }

        //取出农家乐
        $houses = FarmerhouseHouse::find()
            ->select("id,name,price,envphoto as img,address")
            ->where('status=:status and county=:county',[':status'=>FarmerhouseHouse::STATUS_AGREE,':county'=>$addressid])
            ->limit(10)
            ->asArray()
            ->all();

        foreach ($houses as $key => $row)
        {
            $houses[$key]['img']=  Upload::checkGetUrl($row['img']);
            $houses[$key]['url']=  Url::to(['/farmerhouse/site/house-detail','id'=>$row['id']]);
        }


        return $this->render('@template/mobile/farmhouse_list.html',[
            'houses' => \GuzzleHttp\json_encode($houses),
            'address' => \GuzzleHttp\json_encode($address)
        ]);
    }


    public function actionLoadMore()
    {
        $pindex = \Yii::$app->request->post('pindex');
        $pindex = $pindex?$pindex:1;
        $pagesize = 10;
        if(\Yii::$app->request->post('addressid')){
            //取出农家乐
            $houses = FarmerhouseHouse::find()
                ->select("id,name,price,envphoto as img,address")
                ->where('status=:status and county=:county',[':status'=>FarmerhouseHouse::STATUS_AGREE,':county'=>\Yii::$app->request->post('addressid')])
                ->limit($pagesize)->offset(($pindex-1)*$pagesize)
                ->asArray()
                ->all();
        }else{
            //取出农家乐
            $houses = FarmerhouseHouse::find()
                ->select("id,name,price,envphoto as img,address")
                ->where('status=:status',[':status'=>FarmerhouseHouse::STATUS_AGREE])
                ->limit($pagesize)->offset(($pindex-1)*$pagesize)
                ->asArray()
                ->all();
        }


        foreach ($houses as $key => $row)
        {
            $houses[$key]['img']=  Upload::checkGetUrl($row['img']);
            $houses[$key]['url']=  Url::to(['/farmerhouse/site/house-detail','id'=>$row['id']]);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;

        return $houses;

    }


    /**
     * @param $hid
     * @return string
     * 农家乐详情
     */
    public function actionHouseDetail($id)
    {

//        {name:"赵四家农家食宿",price:80,booked:8,leftroom:3,show:"info",info:'<p>详细介绍位于柞水溶洞山下，周边环境优美，开门见山，空气清新。我们家有五间房子，房间设施整洁干净，有完整的卫浴设施。欢迎大家来我家游玩。详细介绍文字，后台可自定义编辑图文混排。</p><img src="/static/images/farmdetail.jpg" alt="">',service:'<p>食宿服务位于柞水溶洞山下，周边环境优美，开门见山，空气清新。我们家有五间房子，房间设施整洁干净，有完整的卫浴设施。欢迎大家来我家游玩。详细介绍文字，后台可自定义编辑图文混排。</p><img src="/static/images/farmdetail.jpg" alt="">',guide:[{img:"/static/images/farmhouse.jpg",content:"玩的很开心，我们公司去游玩，做的菜也很好吃，尤其生态小炒肉，太好吃了，环境特别棒，牛背梁的风景美爆了"},{img:"/static/images/farmhouse.jpg",content:"玩的很开心，我们公司去游玩，做的菜也很好吃，尤其生态小炒肉，太好吃了，环境特别棒，牛背梁的风景美爆了"},{img:"/static/images/farmhouse.jpg",content:"玩的很开心，我们公司去游玩，做的菜也很好吃，尤其生态小炒肉，太好吃了，环境特别棒，牛背梁的风景美爆了"}],comment:[{name:"仔仔",headimg:"http://wx.qlogo.cn/mmopen/47CicbLQOxtWoYIWeEQXzAXeicsEUO3wxEF0IRjQgQNm41K2skIegWuMMhh4icDrcWqleqDcyf7w98gGKe8DS8At8ZQSQ4W8J01/0",star:"5",picture:["/static/images/list1.jpg","/static/images/list2.jpg","/static/images/list1.jpg"],time:"2017-06-12 12:00",content:"不错，值得一去不错，值得一去不错，值得一去不错，值得一去"},{name:"elena",headimg:"http://wx.qlogo.cn/mmopen/47CicbLQOxtWoYIWeEQXzAXeicsEUO3wxEF0IRjQgQNm41K2skIegWuMMhh4icDrcWqleqDcyf7w98gGKe8DS8At8ZQSQ4W8J01/0",star:"3",time:"2017-06-12 12:00",content:"不错，值得一去不错，值得一去不错，值得一去不错，值得一去"}]}
        //农家乐信息
        $detail = (new Query())->select('id,name,envphoto,accommodationphoto,detail as info,price,roomnum,feedlive as service')
            ->from(FarmerhouseHouse::tableName())
            ->where('id=:id',[':id'=>$id])
            ->one();

        //取出今日剩余房间数
        $startdate = strtotime(date('Y-m-d'));
        $enddate = strtotime(date('Y-m-d',strtotime("+1 day")));
        $detail['leftroom'] = FarmerhouseHouse::getLeftnum($id,$startdate,$enddate);



        //预定数
        $detail['booked'] =  (new Query())->select('id')->from(ShopHouseOrder::tableName())->count();


        //轮播
        $envphoto = Upload::checkGetUrl($detail['envphoto'],true,'envphoto');
        $accomodationphoto = Upload::checkGetUrl($detail['accommodationphoto'],true,'accommodationphoto');
        $banner = array_merge($envphoto,$accomodationphoto);
        unset($detail['envphoto'],$detail['accommodationphoto'],$envphoto,$accomodationphoto);

        $detail['show'] = 'info';       //默认展示

        //评价
        $comment = (new Query())->select('c.content,c.star,FROM_UNIXTIME(c.createtime,\'%Y-%m-%d %H:%i:%s\') as `time`,c.picture,u.avatar,u.nickname as name,u.avatar as headimg')
            ->from(FarmerhouseComment::tableName().' as c')
            ->leftJoin(BusinessUser::tableName().' as u','u.id=c.userid')
            ->where('c.houseid=:id and c.status=:status',[':id'=>$id,':status'=>FarmerhouseHouse::STATUS_AGREE])
            ->all();
        foreach ($comment as $key => $row){
            $comment[$key]['picture'] = Upload::checkGetUrl($row['picture'],true,'picture');
        }
        $detail['comment'] = $comment;

        //地区攻略
        $tid = FarmerhouseTravels::find()->select('id')->where('houseid=:id and status=:status',[':id'=>$id,':status'=>FarmerhouseTravels::STATUS_AGREE])->asArray()->all();

        $detail['guide'] = [];
        foreach ($tid as $key => $row){
            $de = (new Query())->select('td.content,td.picture as img')
                ->from(FarmerhouseTravelsDetail::tableName().' as td')
                ->where('travelid=:id',[':id'=>$row['id']])
                ->one();
            $de['img'] = Upload::checkGetUrl($de['img'],false,'img');
            $de['content'] = mb_substr($de['content'],0,50);
            $de['url'] = Url::to(['/business/user/farmer-experience/detail','id'=>$row['id']]);
            $detail['guide'][] = $de;
        }

        return $this->render('@template/mobile/housedetail.html',[
            'banner' => \GuzzleHttp\json_encode($banner),
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);
    }


    /**
     * 攻略
     */
    public function actionRaiders()
    {

        $travels = (new Query())->select('t.title as content,t.id,td.picture as img')->from(FarmerhouseTravels::tableName().' as t')
            ->leftJoin(FarmerhouseTravelsDetail::tableName().' as td','td.travelid=t.id')
            ->where('t.status=:status',[':status'=>FarmerhouseTravels::STATUS_AGREE])
            ->groupBy('t.id')
            ->all();
        foreach ($travels as $key => $row)
        {
            $travels[$key]['url'] = Url::to(['/business/user/farmer-experience/detail','id'=>$row['id']]);
            $travels[$key]['img'] = Upload::checkGetUrl($row['img'],false,'img');
        }

        return $this->render('@template/mobile/farm_experience.html',[
            'travels' => \GuzzleHttp\json_encode($travels)
        ]);

    }



    /**
     * 攻略详情
     */
//    public function actionRaidersDetail($rid)
//    {
//
//        return $this->render('@template/mobile/experience_detail.html',[
//
//        ]);
//
//    }


    /**
     * @return string
     * 评价页面
     */
    public function actionComment($hid)
    {

        $house = FarmerhouseHouse::find()->select('name as title,envdesc as content')->where('id=:id',[':id'=>$hid])->asArray()->one();

        return $this->render('@template/mobile/house_comment.html',[
            'house' => \GuzzleHttp\json_encode($house)
        ]);

    }


    /**
     * @return array
     * 提交评价
     */
    public function actionPostComment()
    {
        $postdata = \Yii::$app->request->post();
        $data = [
            'star' => intval($postdata['score']),
            'content' => $postdata['conmment'],
            'createtime' => time(),
            'userid' => $this->user['userid'],
            'houseid' => $postdata['hid'],
        ];
        if($postdata['img']){
            $infoimgs = Upload::uploadBase64($postdata['img']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($farmer['img'])){
                $infoimgs = $farmer['img'].'|'.$infoimgs;
            }
            $data['picture'] = $infoimgs;
        }
        $res = \Yii::$app->db->createCommand()->insert(FarmerhouseComment::tableName(),$data)->execute();
        //更新订单的书写游记状态
        \Yii::$app->db->createCommand()->update(ShopHouseOrder::tableName(),['ifcomment'=>1],'houseid=:hid and userid=:uid and id=:id',[':hid'=>$postdata['hid'],':uid'=>$this->user['userid'],':id'=>$postdata['oid']])
            ->execute();

        return $res?$this->jsonMsg('评价成功',0):$this->jsonMsg('评价失败',1);

    }






}
